//
//  SinglePageSubViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/11/7.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "SinglePageSubViewController.h"
#import "SubjectContentTableViewCell.h"
#import "SubjectTableHeadView.h"
#import "SubjectContentModel.h"
#import "SubjectMoreEditView.h"
#import "SubjectCheckEditViewController.h"
#import "SubjectStoreEditViewController.h"
#import "SubjectNoEditViewController.h"
#import "CheckRelustViewController.h"
#import "SubjectNameHeadView.h"
@interface SinglePageSubViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)TB_TableView*homeTableView;

@property(nonatomic,strong)SubjectContentModel *Conetnmodel;

@property(nonatomic,strong)UIButton *LookResultBtn;//单张表才存在

@property(nonatomic,strong)UIButton *editBtn;//单张表才存在

@property(nonatomic,strong)SubjectNameHeadView *headView;//单张表才存在

@property(nonatomic,assign)BOOL isShowMoreEdit;

@end

@implementation SinglePageSubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.homeTableView];
    
    [self loadDatas];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(StatuesChange) name:@"StateChange" object:nil];

    // Do any additional setup after loading the view.
}


-(void)StatuesChange
{
    self.confirmState=YES;
    
    self.navigationItem.rightBarButtonItem=nil;
    
    [self loadDatas];
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *Api=[[BaseReqApi alloc]initWithRequestUrl:self.ContentUrl andrequestTime:5 andParams:[self.SubModel mj_keyValuesWithIgnoredKeys:@[@"viewType",@"subjectId"]] andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [Api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        [self stopLoadingAnimation];
 
        self.Conetnmodel=[SubjectContentModel mj_objectWithKeyValues:responseObject];
        
        if (responseStatus==1) {
            //请求成功
            if (self.Conetnmodel.data.list.count==0) {
                
                self.Type=TBNODateType;
                
            }else{
                
                [self.homeTableView reloadData];
                
            }
            
            if (self.SubModel.typeId.length==0) {
                
                 self.headView.SubjectName=self.Conetnmodel.data.subjectName;
            }else{
      
                _Moreblock(self.Conetnmodel.data.subjectName,self.Conetnmodel.data.shopName);
                
            }
           
            
//            self.title=self.Conetnmodel.data.shopName;
            
            if (self.SubModel.typeId.length==0) {
                
                [self.view addSubview:self.LookResultBtn];
                
              if ([self getUserType]==2&&!self.confirmState&&self.CheckLookSelfRecord) {
                
                UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithCustomView:self.editBtn];
                
                self.navigationItem.rightBarButtonItem=item;
                  
              }
                
            }
            
        }else if (responseStatus==0||responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }

    }];

}


-(SubjectNameHeadView*)headView
{
    if (!_headView) {
     
        _headView=[[SubjectNameHeadView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
        
        
    }
    return _headView;
}

-(TB_TableView*)homeTableView
{
    if (!_homeTableView) {

        CGRect frame;
        
        if (kDevice_Is_iPhoneX) {
            
              frame=CGRectMake(0, 0, SCREEN_WIDTH, self.SubModel.typeId.length!=0?SCREEN_HEIGHT-64-50-100-IPhoneXTableHeight:SCREEN_HEIGHT-64-50-IPhoneXTableHeight);
            
        }else{
            
            frame=CGRectMake(0, 0, SCREEN_WIDTH, self.SubModel.typeId.length!=0?SCREEN_HEIGHT-64-50-100:SCREEN_HEIGHT-64-50);
            
        }
        
        _homeTableView=[[TB_TableView alloc]initWithFrame:frame style:UITableViewStylePlain];
        
        if (self.SubModel.typeId.length==0) {
            
            _homeTableView.tableHeaderView=self.headView;
        }
        
        _homeTableView.delegate=self;
        
        _homeTableView.dataSource=self;
        
        _homeTableView.estimatedRowHeight=60;
        
        _homeTableView.tableFooterView=[[UIView alloc]init];
        
        [_homeTableView registerNib:[UINib nibWithNibName:@"SubjectContentTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
      
        
        [_homeTableView registerClass:[SubjectTableHeadView class] forHeaderFooterViewReuseIdentifier:@"head"];
    }
    
    return _homeTableView;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.Conetnmodel.data.list.count;
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SubjectList *data=self.Conetnmodel.data.list[section];
    
    return data.logs.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SubjectList *data=self.Conetnmodel.data.list[indexPath.section];
    
    SubjectLogs *logs=data.logs[indexPath.row];
    
    SubjectContentTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.model=logs;
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 31;
    
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
     SubjectList *data=self.Conetnmodel.data.list[section];
    
    SubjectTableHeadView *head=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    
    head.headTitle=data.name;
    
    head.block=^()
    {
      
        if (!self.confirmState&&[self getUserType]==2&&self.CheckLookSelfRecord) {
            
            SubjectMoreEditView *edit=[[SubjectMoreEditView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andBlock:^(NSInteger isok) {
                
                NSMutableArray *arr=[NSMutableArray array];
                
                [arr addObject:[NSString stringWithFormat:@"%ld",data.typeId]];
                
                
                [self MoreEditWith:arr andisOk:isok];
                
            }];
            
            edit.tipLabel.text=data.name;
            
            [edit popWithSuperView:kAppWindow];
            
            
        }

    };
 
    return head;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //先判断是否角色
    
     SubjectList *data=self.Conetnmodel.data.list[indexPath.section];
    
     SubjectLogs *logs=data.logs[indexPath.row];
    
    if ([self getUserType]==1) {
        
        //商户角色 都可以编辑吧!
        SubjectStoreEditViewController *edit=[SubjectStoreEditViewController new];
        
        edit.logs=logs;
        
        edit.block=^()
        {
            [self loadDatas];
            
        };

        [self.navigationController pushViewController:edit animated:YES];
        
    }else if ([self getUserType]==2)
    {
  
            //未确认
            SubjectCheckEditViewController *edit=[SubjectCheckEditViewController new];
            
              edit.logs=logs;
       
            edit.block=^()
            {
                [self loadDatas];
                
            };
            
            [self.navigationController pushViewController:edit animated:YES];

   
    }else if ([self getUserType]==3)
    {
        //开办方 自己的记录和开办方一样，商户记录只能浏览未通过的
        
        if (self.OpenLookOther) {
            
            //开办方查看商户
            
            SubjectNoEditViewController *NoEdit=[SubjectNoEditViewController new];
            
            NoEdit.logs=logs;
            
            [self.navigationController pushViewController:NoEdit animated:YES];
            
        }else{
        
        SubjectStoreEditViewController *edit=[SubjectStoreEditViewController new];
        
        edit.logs=logs;
        
        edit.block=^()
        {
            [self loadDatas];
            
        };
        [self.navigationController pushViewController:edit animated:YES];
        
    }
        
    }else if ([self getUserType]==4)
    {
        //管理员 所有的只能浏览未通过的
        
        SubjectNoEditViewController *NoEdit=[SubjectNoEditViewController new];
        
          NoEdit.logs=logs;
        
        [self.navigationController pushViewController:NoEdit animated:YES];
        
    }
    
    
}


-(UIButton*)LookResultBtn
{
    if (!_LookResultBtn) {
        
        _LookResultBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        
        if (kDevice_Is_iPhoneX) {
            
             _LookResultBtn.frame=CGRectMake(0, SCREEN_HEIGHT-50-64-IPhoneXTableHeight, SCREEN_WIDTH, 50);
            
        }else{
        
        _LookResultBtn.frame=CGRectMake(0, SCREEN_HEIGHT-50-64, SCREEN_WIDTH, 50);
        }
        _LookResultBtn.backgroundColor=TBColorProvideBtnbg;
        
        _LookResultBtn.titleLabel.font=[UIFont systemFontOfSize:18];
        
        [_LookResultBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_LookResultBtn setTitle:@"查看结果" forState:UIControlStateNormal];
        
        [_LookResultBtn addTarget:self action:@selector(GotoLoookResult:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
    return _LookResultBtn;
}

#pragma mark-查看结果
-(void)GotoLoookResult:(UIButton*)sender
{
    
    if (self.isPop) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
    
    CheckRelustViewController *checkResult=[CheckRelustViewController new];
    
    checkResult.resultId=self.SubModel.resultId;
    
    [self.navigationController pushViewController:checkResult animated:YES];
        
    }
}


#pragma mark-头部编辑

-(UIButton*)editBtn
{
    if (!_editBtn) {
        
        _editBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        _editBtn.frame = CGRectMake(0, 0, 60, 20);
        [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        _editBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_editBtn sizeToFit];
        _editBtn.tintColor=[UIColor clearColor];
        
        [_editBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_editBtn addTarget:self action:@selector(GotoEdit:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _editBtn;
}

#pragma mark-批量编辑
-(void)GotoEdit:(UIBarButtonItem*)sender
{
    SubjectMoreEditView *edit=[[SubjectMoreEditView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andBlock:^(NSInteger isok) {
     
          NSMutableArray *arr=[NSMutableArray array];
        
        for (SubjectList *data in self.Conetnmodel.data.list) {
            
            [arr addObject:[NSString stringWithFormat:@"%ld",data.typeId]];
            
        }
        
        [self MoreEditWith:arr andisOk:isok];
 
    }];
    
    edit.tipLabel.text=self.Conetnmodel.data.subjectName;
    
    [edit popWithSuperView:kAppWindow];
}


-(void)MoreEditWith:(NSArray*)typeIds andisOk:(NSInteger)isok
{
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/inspectBatchEdit.json" andrequestTime:5 andParams:@{@"resultId":self.SubModel.resultId,@"typeIds":[HelpWay arrToJSON:typeIds],@"isOk":[NSString stringWithFormat:@"%ld",isok]} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
        [MBProgressHUD showSuccessMessage:@"修改成功"];
            
        [self loadDatas];
    
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
